package com.kylin.upms.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.kylin.upms.biz.entity.Role;
import com.kylin.upms.biz.entity.User;
import com.kylin.upms.biz.entity.UserSecunity;
import com.kylin.upms.biz.mapper.MongMapper;
import com.kylin.upms.biz.mapper.UserMapper;
import com.kylin.upms.biz.model.OperationLog;
import com.kylin.upms.biz.service.IRoleService;
import com.kylin.upms.biz.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mht
 * @since 2019-09-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {

    @Autowired
    MongMapper mongMapper;
    @Autowired
    MongoTemplate mongoTemplate;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    IRoleService iRoleService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
            logger.info("用户名为:{}",s);
            EntityWrapper wrapper = new EntityWrapper(new User());
            wrapper.eq("username",s);
            User user = this.selectOne(wrapper);
            if(user==null){
                throw new UsernameNotFoundException("用户名不存在");
            }
            List<Role> roleByUserName = iRoleService.getRoleByUserName(s);
            int i = 0;
            String[] roles = new String[roleByUserName.size()];
            for(Role role:roleByUserName){
                roles[i]=role.getName();
                i++;
            }
            UserSecunity userSecunity =  new UserSecunity(s,user.getPassword(), AuthorityUtils.createAuthorityList(roles));
            return userSecunity;
    }

    @Override
    public void insertidb(OperationLog operationLog) {
//        mongoTemplate.save(operationLog,"userdb");
        rabbitTemplate.convertAndSend("itcast",operationLog);
//        System.out.println(operationLog.toString());
//        System.out.println("11111111");
    }

    @Override
    public Page<OperationLog> all(Pageable pageable) {
        return mongMapper.findAll(pageable);
    }
}
